<template>
  <div class="result-page">
    <!-- 生成结果 -->
    <div class="result-section" v-if="task">
      <div class="result-header">
        <h2 class="result-title">生成完成</h2>
        <p class="result-subtitle">您的专属猫咪创意图片</p>
      </div>
      
      <!-- 图片对比 -->
      <div class="image-comparison">
        <!-- 原图 -->
        <div class="image-item">
          <h3 class="image-label">原图</h3>
          <div class="image-container">
            <img :src="task.original_image_url" alt="原始图片" />
          </div>
        </div>
        
        <!-- 箭头 -->
        <div class="arrow-container">
          <van-icon name="arrow" class="arrow-icon" />
        </div>
        
        <!-- 生成图 -->
        <div class="image-item">
          <h3 class="image-label">生成图</h3>
          <div class="image-container" v-if="task.generated_image_url">
            <img :src="task.generated_image_url" alt="生成的图片" @click="previewImage" />
            <div class="image-overlay">
              <van-icon name="eye-o" />
            </div>
          </div>
          <div v-else class="image-placeholder">
            <van-loading />
            <p>生成中...</p>
          </div>
        </div>
      </div>
      
      <!-- 生成信息 -->
      <div class="generation-info">
        <div class="info-card">
          <h3 class="card-title">生成信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <van-icon name="palette" class="info-icon" />
              <div class="info-content">
                <span class="info-label">选择风格</span>
                <span class="info-value">{{ task.style_template?.name || '未知风格' }}</span>
              </div>
            </div>
            <div class="info-item">
              <van-icon name="photo" class="info-icon" />
              <div class="info-content">
                <span class="info-label">图片尺寸</span>
                <span class="info-value">{{ task.width }} × {{ task.height }}</span>
              </div>
            </div>
            <div class="info-item">
              <van-icon name="clock-o" class="info-icon" />
              <div class="info-content">
                <span class="info-label">生成时间</span>
                <span class="info-value">{{ formatDuration() }}</span>
              </div>
            </div>
            <div class="info-item" v-if="task.custom_prompt">
              <van-icon name="edit" class="info-icon" />
              <div class="info-content">
                <span class="info-label">自定义描述</span>
                <span class="info-value">{{ task.custom_prompt }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="action-section" v-if="task?.generated_image_url">
      <div class="action-buttons">
        <van-button 
          type="primary" 
          size="large" 
          icon="download"
          @click="downloadImage"
          class="action-btn primary-btn"
        >
          保存图片
        </van-button>
        
        <van-button 
          type="success" 
          size="large" 
          icon="share"
          @click="shareImage"
          class="action-btn success-btn"
        >
          分享好友
        </van-button>
      </div>
      
      <van-button 
        type="default" 
        size="large" 
        block
        icon="plus"
        @click="generateAgain"
        class="generate-again-btn"
      >
        再生成一张
      </van-button>
    </div>
    
    <!-- 推荐风格 -->
    <div class="recommend-section">
      <h3 class="section-title">试试其他风格</h3>
      <div class="styles-grid" v-if="recommendStyles.length > 0">
        <div 
          v-for="style in recommendStyles" 
          :key="style.id"
          class="style-card"
          @click="useStyle(style)"
        >
          <img 
            :src="style.thumbnail_url || style.preview_image_url || '/placeholder.jpg'" 
            :alt="style.name"
          />
          <p class="style-name">{{ style.name }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useImageStore } from '../stores/image'
import type { ImageTask, StyleTemplate } from '../types'
import { Toast, ImagePreview, Dialog, ActionSheet } from 'vant'

const router = useRouter()
const route = useRoute()
const imageStore = useImageStore()

const task = ref<ImageTask | null>(null)
const recommendStyles = ref<StyleTemplate[]>([])

// 从路由参数获取任务ID
const taskId = computed(() => route.params.taskId as string)

// 格式化生成时长
const formatDuration = () => {
  if (!task.value?.created_at || !task.value?.completed_at) return '-'
  
  const start = new Date(task.value.created_at).getTime()
  const end = new Date(task.value.completed_at).getTime()
  const duration = Math.round((end - start) / 1000) // 秒
  
  if (duration < 60) return `${duration}秒`
  const minutes = Math.floor(duration / 60)
  const seconds = duration % 60
  return `${minutes}分${seconds}秒`
}

// 预览图片
const previewImage = () => {
  if (task.value?.generated_image_url) {
    ImagePreview([task.value.generated_image_url])
  }
}

// 下载图片
const downloadImage = async () => {
  if (!task.value?.generated_image_url) return
  
  try {
    Toast.loading('准备下载...')
    
    // 创建临时链接下载
    const response = await fetch(task.value.generated_image_url)
    const blob = await response.blob()
    
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `meow-ai-${task.value.id}.jpg`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
    
    Toast.clear()
    Toast.success('图片已保存到下载文件夹')
  } catch (error) {
    Toast.clear()
    Toast.fail('下载失败，请长按图片保存')
  }
}

// 分享图片
const shareImage = () => {
  const actions = [
    { name: '微信好友', icon: 'wechat' },
    { name: '朋友圈', icon: 'wechat-moments' },
    { name: '复制链接', icon: 'link' },
    { name: '保存到相册', icon: 'photo' }
  ]
  
  ActionSheet.show({
    title: '分享到',
    actions,
    onSelect: (action: any) => {
      switch (action.name) {
        case '微信好友':
          shareToWechat()
          break
        case '朋友圈':
          shareToMoments()
          break
        case '复制链接':
          copyLink()
          break
        case '保存到相册':
          downloadImage()
          break
      }
    }
  })
}

// 分享到微信
const shareToWechat = () => {
  // 这里需要集成微信SDK
  if (typeof window.wx !== 'undefined') {
    // 微信分享逻辑
    Toast('功能开发中...')
  } else {
    Toast('请在微信中打开')
  }
}

// 分享到朋友圈
const shareToMoments = () => {
  // 这里需要集成微信SDK
  if (typeof window.wx !== 'undefined') {
    // 朋友圈分享逻辑
    Toast('功能开发中...')
  } else {
    Toast('请在微信中打开')
  }
}

// 复制链接
const copyLink = async () => {
  if (!task.value?.generated_image_url) return
  
  try {
    await navigator.clipboard.writeText(task.value.generated_image_url)
    Toast.success('链接已复制')
  } catch (error) {
    Toast.fail('复制失败')
  }
}

// 再生成一张
const generateAgain = () => {
  if (task.value) {
    // 保留原图和风格设置
    imageStore.setUploadedImage({
      url: task.value.original_image_url,
      filename: 'original.jpg'
    })
    
    if (task.value.style_template) {
      imageStore.setSelectedStyle(task.value.style_template)
    }
  }
  
  router.push('/upload')
}

// 使用推荐风格
const useStyle = (style: StyleTemplate) => {
  Dialog.confirm({
    title: '使用新风格',
    message: `确定要使用"${style.name}"风格重新生成吗？`
  }).then(() => {
    if (task.value) {
      imageStore.setUploadedImage({
        url: task.value.original_image_url,
        filename: 'original.jpg'
      })
    }
    
    imageStore.setSelectedStyle(style)
    router.push('/upload')
  })
}

// 加载任务信息
const loadTask = async () => {
  if (!taskId.value) {
    Toast.fail('任务ID不存在')
    router.push('/history')
    return
  }
  
  try {
    const result = await imageStore.getTaskStatus(taskId.value)
    if (result.success) {
      task.value = result.task
      
      if (result.task.status !== 'completed') {
        Toast('图片还在生成中，请稍后查看')
        router.push(`/generate?taskId=${taskId.value}`)
        return
      }
    } else {
      Toast.fail(result.error || '加载任务信息失败')
      router.push('/history')
    }
  } catch (error: any) {
    Toast.fail(error.message || '加载任务信息失败')
    router.push('/history')
  }
}

// 加载推荐风格
const loadRecommendStyles = async () => {
  const result = await imageStore.loadStyleTemplates()
  if (result.success) {
    // 随机选择3个风格推荐
    const shuffled = [...imageStore.styleTemplates].sort(() => 0.5 - Math.random())
    recommendStyles.value = shuffled.slice(0, 3)
  }
}

onMounted(() => {
  loadTask()
  loadRecommendStyles()
})
</script>

<style scoped>
.result-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.result-section {
  background: white;
  border-radius: 20px;
  padding: 30px 20px;
  margin-bottom: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.result-header {
  text-align: center;
  margin-bottom: 30px;
}

.result-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.result-subtitle {
  font-size: 14px;
  color: #666;
}

.image-comparison {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
  gap: 16px;
}

.image-item {
  flex: 1;
  text-align: center;
}

.image-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.image-container {
  position: relative;
  width: 120px;
  height: 120px;
  margin: 0 auto;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.image-overlay .van-icon {
  color: white;
  font-size: 24px;
}

.image-placeholder {
  width: 120px;
  height: 120px;
  margin: 0 auto;
  border: 2px dashed #ddd;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.arrow-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrow-icon {
  font-size: 20px;
  color: #6366f1;
}

.generation-info {
  margin-top: 20px;
}

.info-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
}

.info-grid {
  display: grid;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.info-icon {
  font-size: 16px;
  color: #6366f1;
  margin-top: 2px;
}

.info-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-label {
  font-size: 12px;
  color: #666;
}

.info-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.action-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 16px;
}

.action-btn {
  font-weight: bold;
}

.primary-btn {
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  border: none;
}

.success-btn {
  background: linear-gradient(45deg, #10b981, #34d399);
  border: none;
}

.generate-again-btn {
  color: #6366f1;
  border-color: #6366f1;
}

.recommend-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  text-align: center;
}

.styles-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.style-card {
  text-align: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.style-card:active {
  transform: scale(0.95);
}

.style-card img {
  width: 100%;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 8px;
}

.style-name {
  font-size: 12px;
  color: #333;
}
</style>